//
//  SLIdentityVerificationViewController.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/20.
//


#import "SLIdentityVerificationViewController.h"
#import <YYKit.h>
#import <Masonry.h>
#import "SLProgressTableViewCell.h"
#import "SLSocialSecurityCardTableViewCell.h"
#import "SLCertificationRequirementTableViewCell.h"
#import "SLBottomNextStepButton.h"
#import "SLBottomCameraAlbumButton.h"
#import <TZImagePickerController.h>

#import "FrontCameraViewController.h"
#import "SLAuthenticationPush.h"

@interface SLIdentityVerificationViewController ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate>
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SLBottomNextStepButton *nextStepButton;
@property (nonatomic, strong) SLBottomCameraAlbumButton *cameraAlbumButton;

@property (nonatomic, copy  ) NSArray *OCRData;
@property (nonatomic, copy  ) NSDictionary *data;

// 用户数据
@property (nonatomic, copy  ) NSString *cardType;

@end

@implementation SLIdentityVerificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    @weakify(self);
    [self showNavBar:@"Identity Verification" backBlock:^{
        @strongify(self);
        if (self.isDetail) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [SLAuthenticationPush popToProductDetailViewController:self];
        }
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(0);
        make.top.equalTo(self.navBar.mas_bottom).inset(0);
    }];
    
    if (_isDetail) {
        [self.view addSubview:self.cameraAlbumButton];
        [self.cameraAlbumButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.tableView.mas_bottom);
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(100);
        }];
        if (_bottomCameraAlbumStyle != 1) {
            // 相机
            self.cameraAlbumButton.albumButton.hidden = YES;
        } else {
            // 相机+相册
        }
    } else {
        [self.view addSubview:self.nextStepButton];
        [self.nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.tableView.mas_bottom);
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(100);
        }];
        
        [self requestData];
    }
    
}

- (void)requestData {
    @weakify(self);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [Item1OCRRequestProvider requestOCRWithSuccess:^(NSDictionary * _Nonnull dict) {
        self.OCRData = dict[@"sensitive"];
        dispatch_group_leave(group);
    } failure:^(YTKRequest * _Nonnull request) {
        dispatch_group_leave(group);
    }];
    dispatch_group_enter(group);
    [Item1UserInfoRequestProvider requestGetUserInfoWithProductID:self.productId success:^(NSDictionary * _Nonnull dict) {
        @strongify(self);
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        self.data = [dict deepMutableCopy];
        self.cardType = dict[@"review"][@"monthly"];
        
        NSDictionary *review = dict[@"review"];
        NSString *contained = review[@"contained"]; //证件是否完成 0否1是   "A"
        NSString *elegance = review[@"elegance"]; //证件图片地址
        NSString *monthly = review[@"monthly"]; //已选卡片类型
        NSDictionary *critique = review[@"critique"];
        
        NSString *judged = dict[@"judged"];   //人脸是否完成 0否1是  "B"
        NSString *elegance_face = dict[@"elegance"];  //人脸图片地址
        
        NSString *peppers = dict[@"peppers"];  //图片选择类型：1，相机+相册；2，相机
        dispatch_group_leave(group);
        
    } failure:^(YTKRequest * _Nonnull request) {
        [ResponseToast showToastWithRequest:request];
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        dispatch_group_leave(group);
    }];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isDetail) {
        return 1;
    } else {
        return 2;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_isDetail) {
        SLCertificationRequirementTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLCertificationRequirementTableViewCell" forIndexPath:indexPath];
        if (_type == SLIdentityVerificationIDCard) {
            cell.titleView.titleLabel.text = @"Id Card Portrait Face Photo";
            NSArray *texts = @[
                @"1、Turn off your camera's flash and make sure there's nothing in front of your ID card.",
                @"2、Put the ID card in the frame, with plenty of room on each side.",
                @"3、Turn off your camera's flash and make sure there's nothing in front of your ID card."
            ];
            cell.texts = texts;
            cell.subtitle.text = @"Scan in a well-lit area.";
            //            cell.title.text = @"Certification requirement";
            cell.iv.image = [UIImage imageNamed:@"icon_auth_umid"];
        } else {
            cell.titleView.titleLabel.text = @"Face Recognition";
            NSArray *texts = @[
                @"1、Keep face uncovered and face lighting normal.",
                @"2、Try to keep the background as solid color background, pay attention to the background please do not contain other face information.",
                @"3、Make sure you do it for yourself."
            ];
            cell.texts = texts;
            cell.subtitle.text = @"Shoot In A Well-Lit Area.";
            //            cell.title.text = @"Certification requirement";
            cell.iv.image = [UIImage imageNamed:@"icon_upload_face"];
        }
        return cell;
    } else {
        if (indexPath.row == 0) {
            SLProgressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProgressTableViewCell" forIndexPath:indexPath];
            cell.progressView.stepCount = self.stepCount;
            cell.progressView.currentStep = self.currentStep;
            return cell;
        } else {
            SLSocialSecurityCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLSocialSecurityCardTableViewCell" forIndexPath:indexPath];
            cell.idCardView.imageView.image = [UIImage imageNamed:@"icon_auth_idCard"];
            cell.faceCardView.imageView.image = [UIImage imageNamed:@"icon_auth_face"];
            if (self.cardType.length > 0) {
                cell.selectTitleLabel.text = self.cardType;
            }
            @weakify(self);
            [cell.selectButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
                @strongify(self);
                [self jumpDetail];
            }];
            NSDictionary *review = self.data[@"review"];
            NSString *contained = review[@"contained"]; //证件是否完成 0否1是   "A"
            NSString *elegance = review[@"elegance"]; //证件图片地址
            //NSString *monthly = review[@"monthly"]; //已选卡片类型
            //NSDictionary *critique = review[@"critique"];
            NSString *judged = self.data[@"judged"];   //人脸是否完成 0否1是  "B"
            NSString *elegance_face = self.data[@"elegance"];  //人脸图片地址
            if (contained.sl_intValue == 1) {
                cell.idCardView.isComplete = YES;
                [cell.idCardView.imageView sl_setImageWithURL:elegance];
            }
            if (judged.sl_intValue == 1) {
                cell.faceCardView.isComplete = YES;
                [cell.faceCardView.imageView sl_setImageWithURL:elegance_face];
            }
            [cell.idCardView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
                @strongify(self);
                [self jumpDetail];
            }];
            [cell.faceCardView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
                @strongify(self);
                [self jumpDetail];
            }];
            return cell;
        }
    }
}

- (void)jumpDetail {
    NSDictionary *review = self.data[@"review"];
    NSString *contained = review[@"contained"]; //证件是否完成 0否1是   "A"
    NSString *judged = self.data[@"judged"];   //人脸是否完成 0否1是  "B"
    if (self.cardType.length == 0) {
        // 选择卡片类型
        Analysis.certificate.start = NSDate.date;
        SLOptionChooseView *chooseView = [SLOptionChooseView new];
        @weakify(self);
        @weakify(chooseView);
        [chooseView showOptionIDCardChooseWithCount:self.OCRData.count itemViewCallback:^(SLIDCardOptionChooseCell * _Nonnull item, NSInteger index) {
            @strongify(self);
            item.titleLabel.text = self.OCRData[index][@"veins"];
            [item.icon sl_setImageWithURL:self.OCRData[index][@"rejoicingly"]];
        } confirmCallback:^(NSInteger index) {
            @strongify(self);
            @strongify(chooseView);
            self.cardType = self.OCRData[index][@"veins"];
            [chooseView dismiss];
            [self.tableView reloadData];
            Analysis.certificate.end = NSDate.date;
            [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
                @strongify(self);
                [Analysis sendDataWithProductID:self.productId time:Analysis.certificate];
            }];
        }];
    } else if ([contained sl_intValue] == 0) {
        // 身份证
        SLIdentityVerificationViewController *ctrl = [SLIdentityVerificationViewController new];
        ctrl.isDetail = YES;
        ctrl.productId = self.productId;
        ctrl.cardType = self.cardType;
        ctrl.delegate = self;
        ctrl.type = SLIdentityVerificationIDCard;
        ctrl.bottomCameraAlbumStyle = [self.data[@"peppers"] sl_intValue];
        [self.navigationController pushViewController:ctrl animated:YES];
    } else if ([judged sl_intValue] == 0) {
        // 人脸
        SLIdentityVerificationViewController *ctrl = [SLIdentityVerificationViewController new];
        ctrl.isDetail = YES;
        ctrl.productId = self.productId;
        ctrl.cardType = self.cardType;
        ctrl.delegate = self;
        ctrl.type = SLIdentityVerificationFace;
        ctrl.bottomCameraAlbumStyle = [self.data[@"peppers"] sl_intValue];
        ctrl.cameraAlbumButton.albumButton.hidden = YES;
        [self.navigationController pushViewController:ctrl animated:YES];
    }
}

/// 请求相机和相册权限
- (BOOL)requestCameraPermission {
    BOOL hasCameraPermission = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusAuthorized;
    if (hasCameraPermission) {
        return YES;
    }
    // 1. 检查相机权限
    [self checkCameraPermissionWithCompletion:^(BOOL granted) {
        if (!granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showPermissionAlertWithType:@"camera"];
            });
        }
    }];
    return NO;
}

/// 请求相机和相册权限
- (BOOL)requestAlbumsPermission {
    BOOL hasAlbumsPermission = [PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized;
    if (hasAlbumsPermission) {
        return YES;
    }
    // 2. 检查相册权限
    [self checkPhotoLibraryPermissionWithCompletion:^(BOOL photoGranted) {
        if (!photoGranted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showPermissionAlertWithType:@"albums"];
            });
        }
    }];
    return NO;
}

// 检查相机权限
- (void)checkCameraPermissionWithCompletion:(void(^)(BOOL granted))completion {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusNotDetermined: {
            // 未决定，请求权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (completion) {
                    completion(granted);
                }
            }];
            break;
        }
        case AVAuthorizationStatusRestricted:
        case AVAuthorizationStatusDenied: {
            // 已拒绝
            if (completion) {
                completion(NO);
            }
            break;
        }
        case AVAuthorizationStatusAuthorized: {
            // 已授权
            if (completion) {
                completion(YES);
            }
            break;
        }
    }
}

// 检查相册权限
- (void)checkPhotoLibraryPermissionWithCompletion:(void(^)(BOOL granted))completion {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    switch (status) {
        case PHAuthorizationStatusNotDetermined: {
            // 未决定，请求权限
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (completion) {
                    completion(status == PHAuthorizationStatusAuthorized);
                }
            }];
            break;
        }
        case PHAuthorizationStatusRestricted:
        case PHAuthorizationStatusDenied: {
            // 已拒绝
            if (completion) {
                completion(NO);
            }
            break;
        }
        case PHAuthorizationStatusAuthorized: {
            // 已授权
            if (completion) {
                completion(YES);
            }
            break;
        }
        default:
            if (completion) {
                completion(NO);
            }
            break;
    }
}

// 显示权限提醒弹窗
- (void)showPermissionAlertWithType:(NSString *)type {
    NSString *message = nil;
    if ([type isEqualToString:@"albums"]) {
        message = @"To complete the identity verification process, SulitLoan accesses your photo album. This lets you upload necessary ID photos effortlessly. Please enable photo album permissions in \"Settings.\"";
    } else if ([type isEqualToString:@"camera"]) {
        message = @"For a smooth identity verification, please allow SulitLoan to access your camera. This lets you upload required documents and complete facial recognition easily. Enable camera permissions in \"Settings.\"";
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tips"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    SLSocialSecurityCardTableViewCell *myCell = (SLSocialSecurityCardTableViewCell *)cell;
    if ([myCell isKindOfClass:SLSocialSecurityCardTableViewCell.class]) {
        [myCell layoutIfNeeded];
        [myCell.cardView roundTopCornerRadius:20];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isDetail) {
        return UITableViewAutomaticDimension;
    } else {
        return indexPath.row == 0 ? UITableViewAutomaticDimension : UITableViewAutomaticDimension;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColorHex(#1B1B1B);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:SLProgressTableViewCell.class forCellReuseIdentifier:@"SLProgressTableViewCell"];
        [_tableView registerClass:SLSocialSecurityCardTableViewCell.class forCellReuseIdentifier:@"SLSocialSecurityCardTableViewCell"];
        [_tableView registerClass:SLCertificationRequirementTableViewCell.class forCellReuseIdentifier:@"SLCertificationRequirementTableViewCell"];
    }
    return _tableView;
}

- (SLBottomNextStepButton *)nextStepButton {
    if (!_nextStepButton) {
        _nextStepButton = [SLBottomNextStepButton new];
        @weakify(self);
        [_nextStepButton.nextStepButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            NSDictionary *review = self.data[@"review"];
            NSString *contained = review[@"contained"]; //证件是否完成 0否1是   "A"
            NSString *judged = self.data[@"judged"];   //人脸是否完成 0否1是  "B"
            if ([contained sl_intValue] == 1 && [judged sl_intValue] == 1) {
                [SLAuthenticationPush pushNextPageWithProductID:self.productId view:self.view];
            } else {
                [self jumpDetail];
            }
        }];
    }
    return _nextStepButton;
}
- (SLBottomCameraAlbumButton *)cameraAlbumButton {
    if (!_cameraAlbumButton) {
        _cameraAlbumButton = [SLBottomCameraAlbumButton new];
        @weakify(self);
        [_cameraAlbumButton.albumButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            NSString *deviceModel = [UIDevice jk_deviceModel];
            if ([deviceModel isEqualToString:@"iPad8,6"] || TARGET_OS_SIMULATOR) {
                [self runAction:nil];
            } else {
                // 判断是否有权限
                if (![self requestAlbumsPermission]) {
                    return;
                }
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
                // 你可以通过block或者代理，来得到用户选择的照片.
                [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                    [self runAction:photos.firstObject];
                }];
                [self presentViewController:imagePickerVc animated:YES completion:nil];
            }
        }];
        
        [_cameraAlbumButton.cameraButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            NSString *deviceModel = [UIDevice jk_deviceModel];
            if ([deviceModel isEqualToString:@"iPad8,6"] || TARGET_OS_SIMULATOR) {
                [self runAction:nil];
            } else {
                // 判断是否有权限
                if (![self requestCameraPermission]) {
                    return;
                }
                void(^imageCallback)(UIImage *) = ^(UIImage *image) {
                    [self runAction:image];
                };
                AVCaptureDevicePosition position = (self.type == SLIdentityVerificationIDCard) ? AVCaptureDevicePositionBack : AVCaptureDevicePositionFront;
                BOOL switchCameraButtonHidden = (self.type == SLIdentityVerificationIDCard) ? NO : YES;
                [SLRoutePush route:@"FrontCameraViewController" parameter:@{
                    @"currentCameraPosition": @(position),
                    @"switchCameraButtonHidden": @(switchCameraButtonHidden),
                    @"captureCallback": imageCallback,
                }];
            }
        }];
    }
    return _cameraAlbumButton;
}

- (void)runAction:(UIImage *)image {
    if (!_isDetail) {
        return;
    }
    if (_type == SLIdentityVerificationIDCard) {
        // 身份证
        Analysis.IDCard.start = NSDate.date;
#ifdef DEBUG
        if (!image) {
            image = [UIImage imageNamed:@"idcard.jpg"];
        }
#endif
        @weakify(self);
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [Item1MediaUploadRequestProvider requestUploadMediaWithImageSource:@"1" productId:self.productId peppers:@"11" image:image cardType:self.cardType success:^(NSDictionary * _Nonnull dict) {
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSMutableArray *arr = @[
                @{@"title": @"Name", @"text": dict[@"veins"], @"type":@"txt", @"placeholder": @"Please Enter Your Name"}, // 姓名
                @{@"title": @"Id Number", @"text": dict[@"genial"], @"type": @"txt", @"placeholder": @"Please Enter Your ID Number"}, // 证件号
                @{@"title": @"Date Of Birth", @"text": dict[@"originality"], @"type":@"dateSelect", @"placeholder": @"Please Select Date Of Birth"}, // 出生日期 日-月-年
            ].deepMutableCopy;
            SLOptionChooseView *chooseView = [SLOptionChooseView new];
            @weakify(chooseView);
            [chooseView showOptionInformationChooseWithCount:arr.count itemViewCallback:^(SLInformationOptionChooseCell * _Nonnull item, NSInteger index) {
                item.view.titleLabel.text = arr[index][@"title"];
                item.view.textField.text = arr[index][@"text"];
                item.view.textField.placeholder = arr[index][@"placeholder"];
                item.view.textField.enabled = [arr[index][@"type"] isEqualToString:@"txt"];
                item.view.more.hidden = [arr[index][@"type"] isEqualToString:@"txt"];
                // 输入事件
                [item.view.textField addBlockForControlEvents:UIControlEventEditingChanged block:^(UITextField *sender) {
                    arr[index][@"text"] = sender.text;
                }];
                // 点击事件
                @weakify(item);
                [item.view jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
                    if (index == 2) {
                        @strongify(chooseView);
                        [chooseView endEditing:YES];
                        // 如果选择过日期，则显示选择的日期，没选择过日期，用识别出的日期
                        NSString *birthday = arr[index][@"text"];
                        if (birthday.length == 0) {
                            birthday = dict[@"originality"];
                        }
                        NSDateFormatter *formatter = [NSDateFormatter new];
                        [formatter setDateFormat:@"dd-MM-yyyy"]; // 出生日期 日-月-年
                        NSDate *date = [formatter dateFromString:birthday];
                        [SLDatePickerView showDateChooseWithDefaultDate:date confirmCallback:^(NSDate *select) {
                            @strongify(item);
                            NSDateFormatter *formatter = [NSDateFormatter new];
                            [formatter setDateFormat:@"dd-MM-yyyy"]; // 出生日期 日-月-年
                            NSString *date = [formatter stringFromDate:select];
                            arr[index][@"text"] = date;
                            item.view.textField.text = date;
                        }];
                    }
                }];
            } confirmCallback:^(NSInteger index) {
                @strongify(self);
                @strongify(chooseView);
                [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [Item1UserInfoRequestProvider requestUpdateUserInfoWithBirthday:arr[2][@"text"] cardNumber:arr[1][@"text"] username:arr[0][@"text"] cardType:self.cardType success:^(NSDictionary * _Nonnull dict) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    [chooseView dismiss];
                    [self.navigationController popViewControllerAnimated:YES];
                    if ([self.delegate respondsToSelector:@selector(requestData)]) {
                        [self.delegate requestData];
                    }
                    Analysis.IDCard.end = NSDate.date;
                    [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
                        @strongify(self);
                        [Analysis sendDataWithProductID:self.productId time:Analysis.IDCard];
                    }];
                } failure:^(YTKRequest * _Nonnull request) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    [ResponseToast showToastWithRequest:request];
                }];
            }];
        } failure:^(YTKRequest * _Nonnull request) {
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [ResponseToast showToastWithRequest:request];
        }];
    } else if (_type == SLIdentityVerificationFace) {
        // 人脸认证
        Analysis.recognition.start = NSDate.date;
#ifdef DEBUG
        if (!image) {
            image = [UIImage imageNamed:@"face.jpg"];
        }
#endif
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        @weakify(self);
        [Item1MediaUploadRequestProvider requestUploadMediaWithImageSource:@"2" productId:self.productId peppers:@"10" image:image cardType:self.cardType success:^(NSDictionary * _Nonnull dict) {
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.navigationController popViewControllerAnimated:YES];
            if ([self.delegate respondsToSelector:@selector(requestData)]) {
                [self.delegate requestData];
            }
            
            Analysis.recognition.end = NSDate.date;
            [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
                @strongify(self);
                [Analysis sendDataWithProductID:self.productId time:Analysis.recognition];
            }];
            
        } failure:^(YTKRequest * _Nonnull request) {
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [ResponseToast showToastWithRequest:request];
        }];
    }
}

@end
